package com.windowes.weichang.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.windowes.weichang.access.UserContext;
import com.windowes.weichang.common.ServerResponse;
import com.windowes.weichang.component.redis.RedisService;
import com.windowes.weichang.component.redis.UserKey;
import com.windowes.weichang.dao.*;
import com.windowes.weichang.dto.ShopUserDTO;
import com.windowes.weichang.pojo.*;
import com.windowes.weichang.utils.RegexUtils;
import com.windowes.weichang.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/***
 *
 * @author: yangqing
 * @email: qing.yang@bangdao-tech.com
 * @createTime: 2018/5/23 下午9:11
 * @description:
 *
 **/
@Service
@Slf4j
public class UserService {

    public static final String COOKI_NAME_TOKEN = "token";

    @Autowired
    RedisService redisService;

    @Autowired
    WUserMapper userMapper;
    @Autowired
    UserCoreService userCoreService;

    @Autowired
    DemandMapper demandMapper;
    @Autowired
    ShopUserRelationMapper shopUserRelationMapper;
    @Autowired
    DemandItemMapper demandItemMapper;
    @Autowired
    WShopMapper shopMapper;


    public ServerResponse searchByKw(String kw) {
        if (StringUtils.isEmpty(kw)) {
            return ServerResponse.createBySuccessMessage("请输入关键字");
        }
        List<WUser> users = userMapper.selectByKw(kw);
        if (users != null && !users.isEmpty()) {
            return ServerResponse.createBySuccess(users);
        }
        return ServerResponse.createBySuccessMessage("未找到数据");
    }

    /**
     * 用户登陆
     *
     * @param phone
     * @param password
     * @return
     */
    public ServerResponse login(HttpServletResponse response, String phone, String password) {
        if (StringUtils.isBlank(phone)) {
            return ServerResponse.createByErrorMessage("请输入手机号");
        }

        if (!RegexUtils.isMobileExact(phone)) {
            return ServerResponse.createByErrorMessage("请输入正确手机号！");
        }

        if (StringUtils.isBlank(password)) {
            return ServerResponse.createByErrorMessage("请输入密码");
        }

        ServerResponse<WUser> userByPhone = userCoreService.getUserByPhone(phone);
        if (userByPhone.isSuccess()) {
            WUser user = userByPhone.getData();
            user.setNeedUpdatePassword(false);
            if (StringUtils.equals(user.getPassword(), "123456")) {
                user.setNeedUpdatePassword(true);
            }
            if (password.equals(user.getPassword())) {
                if (!(user.getFrom().intValue() == (1))) {
                    return ServerResponse.createByErrorMessage("平台账号管理账号无法登陆!");
                }
                String token = UUIDUtil.uuid();
                addCookie(response, token, user);
                //清空密码信息
                user.setPassword(null);
                user.setToken(token);
                userMapper.updateLastLoginTime(user.getId());
                return ServerResponse.createBySuccess("登录成功!", user);
            }
        }
        return ServerResponse.createByErrorMessage("登录失败!");
    }

    /**
     * 手机号登陆
     *
     * @param phone
     * @param smsCode
     * @return
     */
    public ServerResponse loginWithSmsCode(HttpServletResponse response, String phone, String smsCode) {

        ServerResponse checkSmsCodeResp = checkSmsCode("login:" + phone, smsCode);
        if (!checkSmsCodeResp.isSuccess()) {
            return checkSmsCodeResp;
        }

        if (!RegexUtils.isMobileExact(phone)) {
            return ServerResponse.createByErrorMessage("请输入正确手机号！");
        }
        //查询是否存在用户
        ServerResponse<WUser> userByPhone = userCoreService.getUserByPhone(phone);
        if (!userByPhone.isSuccess()) {
            //用户不存在,直接注册
            WUser wUser = new WUser();
            wUser.setPhone(phone);
            wUser.setPassword("123456");
            wUser.setFrom((short) 1);
            userMapper.insertSelective(wUser);
            return login(response, wUser.getPhone(), wUser.getPassword());
        }
        //调用登陆方法
        return login(response, phone, userByPhone.getData().getPassword());
    }

    /**
     * 校验验证码
     *
     * @param key
     * @param smsCode
     * @return
     */
    private ServerResponse checkSmsCode(String key, String smsCode) {
        if (!redisService.exists(key)) {
            return ServerResponse.createByErrorMessage("验证码已过期,请重新获取!");
        }
        String smsCodeSaved = redisService.get(key);
        if (!StringUtils.equals(smsCodeSaved, smsCode)) {
            return ServerResponse.createByErrorMessage("验证码不正确,请确认!");
        }
        return ServerResponse.createBySuccessMessage("验证码校验通过!");
    }

    /**
     * 普通用户注册
     *
     * @param response
     * @param phone
     * @param smsCode
     * @return
     */
    public ServerResponse register(HttpServletResponse response, String phone, String smsCode) {
        ServerResponse checkSmsCodeResp = checkSmsCode("register:" + phone, smsCode);
        if (!checkSmsCodeResp.isSuccess()) {
            return checkSmsCodeResp;
        }

        if (!RegexUtils.isMobileExact(phone)) {
            return ServerResponse.createByErrorMessage("请输入正确手机号！");
        }
        //查询用户是否存在
        ServerResponse userByPhone = userCoreService.getUserByPhone(phone);
        if (userByPhone.isSuccess()) {
            return ServerResponse.createByErrorMessage("该手机号已注册,请直接登录!");
        }
        WUser wUser = new WUser();
        wUser.setPhone(phone);
        wUser.setPassword("123456");
        wUser.setFrom((short) 1);
        userMapper.insertSelective(wUser);
        ServerResponse login = login(response, wUser.getPhone(), wUser.getPassword());
        if (login.isSuccess()) {
            return ServerResponse.createBySuccess("注册成功!", login.getData());
        }
        return login;
    }

    /**
     * 重置密码
     *
     * @param phone
     * @param smsCode
     * @return
     */
    public ServerResponse resetPassword(String phone, String smsCode, String password) {

        ServerResponse checkSmsCodeResp = checkSmsCode("reset:" + phone, smsCode);
        if (!checkSmsCodeResp.isSuccess()) {
            return checkSmsCodeResp;
        }

        if (!RegexUtils.isMobileExact(phone)) {
            return ServerResponse.createByErrorMessage("请输入正确手机号！");
        }
        if (StringUtils.isEmpty(password)) {
            return ServerResponse.createByErrorMessage("请输入新密码！");
        }
        if (StringUtils.equals("123456", password)) {
            return ServerResponse.createByErrorMessage("密码不能修改为123456！");
        }

        //查询用户是否存在
        ServerResponse<WUser> userByPhone = userCoreService.getUserByPhone(phone);
        if (!userByPhone.isSuccess()) {
            return ServerResponse.createByErrorMessage("用户不存在!");
        }
        WUser data = userByPhone.getData();
        data.setPassword(password);
        userMapper.updateByPrimaryKeySelective(data);
        return ServerResponse.createBySuccessMessage("密码已重置为123456,请尽快修改!");
    }


    private void addCookie(HttpServletResponse response, String token, WUser user) {
        redisService.setUser(token, user);
        Cookie cookie = new Cookie(COOKI_NAME_TOKEN, token);
        cookie.setMaxAge(UserKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }


    public ServerResponse login4Manage(HttpServletResponse response, String phone, String password) {
        if (StringUtils.isBlank(phone)) {
            return ServerResponse.createByErrorMessage("请输入手机号");
        }

        if (!RegexUtils.isMobileExact(phone)) {
            return ServerResponse.createByErrorMessage("请输入正确手机号！");
        }

        if (StringUtils.isBlank(password)) {
            return ServerResponse.createByErrorMessage("请输入密码");
        }

        ServerResponse<WUser> userByPhone = userCoreService.getUserByPhone(phone);
        if (userByPhone.isSuccess()) {
            WUser user = userByPhone.getData();
            if (password.equals(user.getPassword())) {
                if (!(user.getFrom().intValue() == 0)) {
                    return ServerResponse.createByErrorMessage("登陆异常,非平台账号管理账号!");
                }
                String token = UUIDUtil.uuid();
                addCookie(response, token, user);
                //清空密码信息
                user.setToken(token);
                user.setPassword(null);
                userMapper.updateLastLoginTime(user.getId());
                return ServerResponse.createBySuccess("登录成功!", user);
            }
        }
        return ServerResponse.createByErrorMessage("登录失败,请检查用户名密码是否正确!");
    }


    /**
     * 人员列表
     * type: 0- 员工 1-客户
     *
     * @param pageNo
     * @param pageSize
     * @param type
     * @return
     */
    public ServerResponse users(int pageNo, int pageSize, int type, String keyword) {
        Page<WUser> page = new Page<>(pageNo, pageSize);
        page.setRecords(userMapper.selectByPage(page, type, keyword));
        return ServerResponse.createBySuccess(page);
    }


    @Autowired
    DistrictService districtService;

    public ServerResponse addCustomer(WUser user) {
        if (user == null) {
            return ServerResponse.createByErrorMessage("请提交人员信息");
        }

        if (!RegexUtils.isMobileExact(user.getPhone())) {
            return ServerResponse.createByErrorMessage("请输入正确手机号！");
        }

        //查询用户是否存在
        ServerResponse userByPhone = userCoreService.getUserByPhone(user.getPhone());
        if (userByPhone.isSuccess()) {
            return ServerResponse.createByErrorMessage("账号已存在,请检查!");
        }

        try {
            if ((user.getProvinceId() != null)
                    && (user.getCityId() != null)
                    && (user.getAreaId() != null)
                    && (user.getStreetId() != null)) {
                ServerResponse<String> standardAddress = districtService.getStandardAddress(user.getProvinceId(), user.getCityId(), user.getAreaId(), user.getStreetId());
                user.setStandardAddress(standardAddress.getData());
            }

            if (user.getId() == null) {
                user.setFrom((short) 1);
                user.setPassword("123456");
                userMapper.insertSelective(user);
            } else {
                userMapper.updateByPrimaryKeySelective(user);
            }
            return ServerResponse.createBySuccessMessage("客户添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("系统异常！");
        }

    }


    /**
     * 根据token获取人员信息
     *
     * @return
     */
    public ServerResponse<WUser> getUserByToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return ServerResponse.createByErrorMessage("请提交token");
        }
        WUser user = redisService.getUser(token);
        if (user != null) {
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("用户未登陆");
    }

    /**
     * 根据id获取人员信息
     *
     * @return
     */
    public ServerResponse<WUser> getUserById(Integer id) {
        if (id == null) {
            return ServerResponse.createByErrorMessage("请提交id!");
        }
        WUser user = userMapper.selectByPrimaryKey(id);
        if (user != null) {
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("用户不存在,请核实");
    }


    public ServerResponse updatePwd(String oldPwd, String newPwd) {
        if (StringUtils.isEmpty(oldPwd)) {
            return ServerResponse.createByErrorMessage("请提交原密码!");
        }
        if (StringUtils.isEmpty(newPwd)) {
            return ServerResponse.createByErrorMessage("请提交新密码!");
        }
        if (StringUtils.equals(oldPwd, newPwd)) {
            return ServerResponse.createByErrorMessage("原密码与新密码不能一致,请核实!");
        }

        WUser user = UserContext.getUser();
        WUser wUser = userMapper.selectByPrimaryKey(user.getId());
        if (!StringUtils.equals(oldPwd, wUser.getPassword())) {
            return ServerResponse.createByErrorMessage("原密码错误,请核实!");
        }
        wUser.setPassword(newPwd);
        userMapper.updateByPrimaryKeySelective(wUser);
        return ServerResponse.createBySuccessMessage("操作成功!");
    }

    public ServerResponse getUserInfo() {
        WUser user = UserContext.getUser();
        WUser wUser = userMapper.selectByPrimaryKey(user.getId());

        wUser.setNeedUpdatePassword(false);
        if (StringUtils.equals(wUser.getPassword(), "123456")) {
            wUser.setNeedUpdatePassword(true);
        }
        wUser.setPassword(null);
        //查询当前店铺
        WShop wShop = shopMapper.selectByUserId(wUser.getId(), null);
        wUser.setShopInfo(wShop);
        return ServerResponse.createBySuccess("获取成功!", wUser);
    }


    public ServerResponse updateSelf(WUser user) {
        if (user == null) {
            return ServerResponse.createByErrorMessage("请提交人员信息");
        }

        if (!RegexUtils.isMobileExact(user.getPhone())) {
            return ServerResponse.createByErrorMessage("请输入正确手机号！");
        }

        WUser user1 = UserContext.getUser();
        user.setId(user1.getId());
        try {
            if ((user.getProvinceId() != null)
                    && (user.getCityId() != null)
                    && (user.getAreaId() != null)
                    && (user.getStreetId() != null)) {
                ServerResponse<String> standardAddress = districtService.getStandardAddress(user.getProvinceId(), user.getCityId(), user.getAreaId(), user.getStreetId());
                user.setStandardAddress(standardAddress.getData());
            }
            userMapper.updateByPrimaryKeySelective(user);
            return ServerResponse.createBySuccessMessage("操作成功！");
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("系统异常！");
        }
    }

    /**
     * 【商户】客户列表
     *
     * @param pageNo
     * @param pageSize
     * @param shopId
     * @param keyword
     * @return
     */
    public ServerResponse shopCustomers(int pageNo, int pageSize, Integer shopId, String keyword) {
        Page<ShopUserRelation> page = new Page<>(pageNo, pageSize);
        page.setRecords(shopUserRelationMapper.selectByPage(page, shopId, keyword));
        if (page.getRecords().isEmpty()) {
            return ServerResponse.createByErrorMessage("暂无客户!");
        }
        Page pageF = new Page();
        BeanUtils.copyProperties(page, pageF);
        List<ShopUserRelation> records = page.getRecords();
        ShopUserDTO shopUserDTO = null;
        List<ShopUserDTO> shopUserDTOS = Lists.newArrayList();
        for (ShopUserRelation demand : records) {
            shopUserDTO = new ShopUserDTO();
            shopUserDTO.setDtlAddress(demand.getDtlAddress());
            shopUserDTO.setName(demand.getName());
            shopUserDTO.setPhone(demand.getPhone());
            shopUserDTO.setUserId(demand.getUserId());
            WUser wUser = userMapper.selectByPrimaryKey(demand.getUserId());
            //传到单条
            List<Demand> demands = demandMapper.selectDemads(demand.getUserId(), demand.getShopId());
            if (!demands.isEmpty()) {
                Demand demand1 = demands.get(0);
                shopUserDTO.setIntentLevel(demand1.getIntentLevel().intValue());
                List<DemandItem> demandItems = demandItemMapper.selectByDemandId(demand1.getId());
                if (!demandItems.isEmpty()) {
                    shopUserDTO.setYear(demandItems.get(0).getYear());
                }
                shopUserDTO.setDemandId(demand1.getId());
                shopUserDTO.setArea(demand1.getArea() + "");
                shopUserDTO.setIntent(demand1.getIntent());
                shopUserDTO.setShape(demand1.getShape());
                shopUserDTO.setCategory(demand1.getShape());
                shopUserDTO.setLife(wUser.getLife());
                shopUserDTO.setIntent(demand1.getIntent());
            }
            shopUserDTOS.add(shopUserDTO);
        }
        pageF.setRecords(shopUserDTOS);
        return ServerResponse.createBySuccess(pageF);
    }

    public ServerResponse loginOff() {
        return ServerResponse.createBySuccessMessage("已登出!");
    }


    public ServerResponse customerInfo(Integer demandId) {
        Demand demand = demandMapper.selectByPrimaryKey(demandId);
        ShopUserDTO shopUserDTO = new ShopUserDTO();
        WUser wUser = userMapper.selectByPrimaryKey(demand.getUserId());
        shopUserDTO.setIntentLevel(demand.getIntentLevel().intValue());
        List<DemandItem> demandItems = demandItemMapper.selectByDemandId(demand.getId());
        if (!demandItems.isEmpty()) {
            shopUserDTO.setYear(demandItems.get(0).getYear());
        }
        shopUserDTO.setDtlAddress(demand.getDtladdress());
        shopUserDTO.setPhone(demand.getPhone());
        shopUserDTO.setName(demand.getName());
        shopUserDTO.setDemandId(demand.getId());
        shopUserDTO.setArea(demand.getArea() + "");
        shopUserDTO.setIntent(demand.getIntent());
        shopUserDTO.setShape(demand.getShape());
        shopUserDTO.setCategory(demand.getShape());
        shopUserDTO.setLife(wUser.getLife());
        shopUserDTO.setIntent(demand.getIntent());
        return ServerResponse.createBySuccess(shopUserDTO);
    }
}
